<template>
  <div class="mod-comment">
    <avue-crud
      ref="crudRef"
      :data="commentData"
      :option="commentOption"
      :page="page"
      :table-loading="dataListLoading"
      @on-load="getCommentList"
      @row-del="handleDelete"
      @search-change="searchChange"
      @selection-change="selectionChange">
      
      <!-- 敏感词高亮显示 -->
      <template #content="{row}">
        <div v-html="highlightSensitive(row.content)"></div>
      </template>

      <!-- 批量操作栏 -->
      <template #menu-left>
        <el-button
          v-if="isAuth('social:comment:delete')"
          type="danger"
          :disabled="dataListSelections.length <= 0"
          @click="handleBatchDelete">
          批量删除
        </el-button>
      </template>
    </avue-crud>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'
const page = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 20
})

const commentData = ref([])
const dataListLoading = ref(false)
const dataListSelections = ref([])
const sensitiveWords = ref(['政治敏感词', '广告', '脏话示例']) // 可从后端动态加载

const commentOption = reactive({
  title: '评论管理',
  border: true,
  index: true,
  menuAlign: 'center',
  dialogWidth: '60%',
  selection: true,
  index: true,
  indexLabel: '序号',
  indexWidth: 60,
  menuAlign: 'center',
  align: 'center',
  column: [
    {
      label: '用户信息',
      prop: 'userInfo',
      children: [
        { label: '用户ID', prop: 'userId', width: 120 },
        { label: '昵称', prop: 'nickName', width: 150 }
      ],
      overHidden: true
    },
    {
      label: '评论内容',
      prop: 'content',
      span: 24,
      overHidden: true,
      slot: true,
      rules: [{ required: true, min: 2, max: 500 }]
    },
    {
      label: '状态', 
      prop: 'status',
      type: 'select',
      dicData: [
        { label: '正常', value: 1 },
        { label: '已删除', value: 0 }
      ],
      search: true
    },
    {
      label: '评论时间',
      prop: 'createdAt',
      type: 'datetime',
      format: 'yyyy-MM-dd HH:mm',
      valueFormat: 'timestamp',
      searchRange: true
    }
  ]
})

// 加载敏感词（可选）
onMounted(async () => {
  try {
    const { data } = await http.get('/sys/sensitive-words')
    sensitiveWords.value = data
  } catch (error) {
    ElMessage.error('敏感词加载失败')
  }
})

// 获取评论列表
const getCommentList = async (pageParam, params, done) => {
  dataListLoading.value = true
  try {
    const { data } = await http({
      url: http.adornUrl('/social/comment/page'),
      method: 'get',
      params: http.adornParams({
        current: pageParam?.currentPage || page.currentPage,
        size: pageParam?.pageSize || page.pageSize,
        ...params
      })
    })
    commentData.value = data.records.map(item => ({
      ...item,
      createdAt: new Date(item.createdAt).toISOString()
    }))
    page.total = data.total
    page.currentPage = data.current
    page.pageSize = data.size
  } catch (error) {
    ElMessage.error('评论加载失败')
  } finally {
    dataListLoading.value = false
    done && done()
  }
}

// 高亮敏感词
const highlightSensitive = (text) => {
  return sensitiveWords.value.reduce((acc, word) => {
    const regex = new RegExp(word, 'gi')
    return acc.replace(regex, match => 
      `<span class="sensitive-word">${match}</span>`
    )
  }, text)
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除这条评论？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消', 
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl(`/social/comment/${row.commentId}`),
      method: 'delete'
    }).then(() => {
      ElMessage.success('删除成功')
      getCommentList(page)
    })
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = dataListSelections.value.map(item => item.commentId)
  if(ids.length === 0) return

  ElMessageBox.confirm(
    `确认删除选中的${ids.length}条评论？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/social/comment/batch'),
      method: 'delete',
      data: ids
    }).then(() => {
      ElMessage.success('批量删除成功')
      getCommentList(page)
    })
  })
}

const searchChange = (params, done) => {
  page.currentPage = 1
  getCommentList(page, params, done)
}

const selectionChange = (val) => {
  dataListSelections.value = val
}
</script>

<style scoped>
.sensitive-word {
  color: #ff4d4f;
  background-color: #fff2f0;
  padding: 2px 4px;
  border-radius: 2px;
}
</style>
